<?php
namespace App\Repositories;
use Bosnadev\Repositories\Contracts\RepositoryInterface;
abstract class _treeRepository extends _appRepository
{
    private $order = 0;
    public function GetMenu()
    {
        $this->applyCriteria();
        return $this->model->orderBy('Orders', 'asc')->orderBy('Sort', 'asc')->get();
    }
    /**
     * @param array $columns
     * @return mixed
     */
    public function AllByOrder($orders = 'Orders', $sort = 'asc', $columns = array('*'), $where = [])
    {
        $this->applyCriteria();
        $model = $this->model;
        foreach ($where as $field => $value) {
            if ($value instanceof \Closure) {
                $model = $model->where($value);

            }
            elseif (is_array($value)) {
                if (count($value) === 3) {
                    list($field, $operator, $search) = $value;
                    $model = $model->where($field, $operator, $search);

                }
                elseif (count($value) === 2) {
                    list($field, $search) = $value;
                    $model = $model->where($field, '=', $search);
                }
            }
            else {
                $model = $model->where($field, '=', $value);
            }
        }
        return $model->orderBy($orders, $sort)->get($columns);
    }
    public function GetModel($id)
    {
        $this->applyCriteria();
        return $this->model->where('ID', '=', $id)->first();
    }
    public function UpdateAll()
    {
        $this->order = 0;
        $this->UpdateNodes();
    }
    private function UpdateNodes($ParentID = 0, $Depth = 0)
    {
        $list = $this->GetListByParentID($ParentID);
       
        if (!empty($list)) {
            $sort = 0;
            foreach ($list as $val) {
                $allid = $this->GetAllID($val->ID);

                $this->model->find($val->ID)->update(['Orders' => $this->order, 'Sort' => $sort, 'Depth' => $Depth, 'AllID' => $allid]);
                $sort++;
                $this->order++;
                $this->UpdateNodes($val->ID, $Depth + 1);

            }
        }

    }
    private function GetAllID($ID)
    {
        $model = $this->model->where('ID', $ID)->first();
        $array = array();
        $array[] = $model->ID . "";

        while (!empty($model)) {
            $array[] = $model->ParentID;
            $model = $this->model->where('ID', $model->ParentID)->first();

        }
        $array = array_reverse($array);
        return ',' . join(',', $array) . ',';
    }
    public function GetListByParentID($ParentID = 0)
    {
        return $this->model->where('ParentID', '=', $ParentID)->orderBy('Sort', 'asc')->get();
    }
}